/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tony.core.jackson

/**
 * Jackson 反序列化注入
 * @author tangli
 * @date 2023/09/28 19:16
 */
import com.fasterxml.jackson.annotation.JacksonInject
import com.fasterxml.jackson.annotation.OptBoolean
import com.fasterxml.jackson.databind.BeanProperty
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.InjectableValues
import java.lang.reflect.Constructor
import tony.core.exception.ApiException
import tony.core.utils.annotation
import tony.core.utils.asToNotNull

/**
 * Jackson 反序列化注入.
 *
 * @author tangli
 * @date 2023/09/28 19:16
 */
public class DeserializeInjectableValuesBySupplier(
    private val values: Map<String, DeserializeInjectableValueSupplier>,
) : InjectableValues() {
    override fun findInjectableValue(
        ctxt: DeserializationContext,
        valueId: Any,
        property: BeanProperty,
        beanInstance: Any?,
        optional: Boolean?,
        useInput: Boolean?,
    ): Any? {
        if (property.member.member is Constructor<*>) {
            throw ApiException("please do not use @JacksonInject in constructor")
        }
        val annotated = property.member.annotated
        val annotation = annotated.annotation(JacksonInject::class.java)
        val internalUseInput =
            if (annotation?.useInput == null || annotation.useInput == OptBoolean.DEFAULT) {
                null
            } else {
                annotation.useInput == OptBoolean.TRUE
            }
        val key = valueId.asToNotNull<String>()
        val ob = values[key]?.value(property, beanInstance)
        if (internalUseInput == true && beanInstance != null && ob == null) {
            return property.member.getValue(beanInstance)
        }
        if (
            ob == null &&
            !values.containsKey(key) &&
            (optional == false || optional == null) &&
            ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_INJECT_VALUE)
        ) {
            throw ctxt.missingInjectableValueException(
                "No injectable value with id '$key' found (for property '${property.name}')",
                valueId,
                property,
                beanInstance
            )
        }
        return ob
    }

    @Deprecated("Deprecated in Java")
    override fun findInjectableValue(
        valueId: Any,
        ctxt: DeserializationContext,
        property: BeanProperty,
        beanInstance: Any?,
    ): Any? =
        findInjectableValue(ctxt, valueId, property, beanInstance, null, null)
}

/**
 * Jackson 反序列化注入 Supplier.
 * @author tangli
 * @date 2023/09/13 19:17
 */
public interface DeserializeInjectableValueSupplier {
    public val name: String

    public fun value(
        property: BeanProperty,
        instance: Any?,
    ): Any
}

/**
 * 抽象Jackson 反序列化注入 Supplier.
 * @author tangli
 * @date 2023/09/13 19:18
 */
public abstract class AbstractDeserializeInjectableValueSupplier(
    override val name: String,
) : DeserializeInjectableValueSupplier {
    public constructor(type: Class<*>) : this(type.name)
}
